package com.example.redpocket.configuration.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

public class RedisLockUtil {

    private static RedissonClient redissonClient;

    public void setRedissonClient(RedissonClient redissonClient) {
        RedisLockUtil.redissonClient = redissonClient;
    }

    public static RLock lock(String lockName){
        RLock lock=redissonClient.getLock(lockName);
        lock.lock();
        return lock;
    }

    public static void unlock(String lockName){
        redissonClient.getLock(lockName).unlock();
    }

    public static void unlock(RLock lock){
        lock.unlock();
    }

    public static RLock lock(String lockKey,int timeout){
        RLock lock=redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

    public static RLock lock(String lockKey, TimeUnit unit ,int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    public static boolean tryLock(String lockKey,TimeUnit unit,int waitTime,int leaseTime){
        RLock lock=redissonClient.getLock(lockKey);
        try{
            return lock.tryLock(waitTime,leaseTime,unit);
        }catch (InterruptedException e) {
            return false;
        }
    }
}
